import React from 'react'
import { Button, Space } from 'antd'
import {
  CheckCircleOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons'
import { SaveStatus } from '../../hooks/useAutoSave'
import './styles.css'

export interface SaveIndicatorProps {
  status: SaveStatus
  lastSavedAt: Date | null
  onSaveNow?: () => void
}

/**
 * 格式化相对时间
 */
function formatRelativeTime(date: Date): string {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const seconds = Math.floor(diff / 1000)

  if (seconds < 60) return '刚刚'
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟前`
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时前`
  return date.toLocaleString('zh-CN')
}

/**
 * 保存状态指示器组件
 */
export const SaveIndicator: React.FC<SaveIndicatorProps> = ({
  status,
  lastSavedAt,
  onSaveNow
}) => {
  const getStatusConfig = () => {
    switch (status) {
      case SaveStatus.SAVED:
        return {
          icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
          text: lastSavedAt ? `已保存 (${formatRelativeTime(lastSavedAt)})` : '已保存',
          color: '#52c41a'
        }
      case SaveStatus.SAVING:
        return {
          icon: <LoadingOutlined style={{ color: '#1890ff' }} />,
          text: '保存中...',
          color: '#1890ff'
        }
      case SaveStatus.UNSAVED:
        return {
          icon: <ExclamationCircleOutlined style={{ color: '#faad14' }} />,
          text: '有未保存更改',
          color: '#faad14'
        }
      case SaveStatus.ERROR:
        return {
          icon: <CloseCircleOutlined style={{ color: '#ff4d4f' }} />,
          text: '保存失败',
          color: '#ff4d4f'
        }
    }
  }

  const config = getStatusConfig()

  return (
    <div className={`save-indicator ${status === SaveStatus.SAVING ? 'saving' : ''}`}>
      <Space size="small">
        {config.icon}
        <span style={{ color: config.color }}>{config.text}</span>
        {status === SaveStatus.ERROR && onSaveNow && (
          <Button type="link" size="small" onClick={onSaveNow}>
            重试
          </Button>
        )}
      </Space>
    </div>
  )
}

export default SaveIndicator
